<script lang="ts" setup>
import type { DataType } from './types';

import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { $t } from '@vben/locales';
import { Page } from '@vben/common-ui';

import { Button, message, Popconfirm, Space ,Modal} from 'ant-design-vue';
import {  VbenButton } from '@vben/common-ui';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getEmailLog ,deleteEmailTemplat,deleteMultiple} from '#/api/admin/emailLog';
import Icon from '#/components/Icons';
import { formatImagesList, queryStringToObject } from '#/utils';



const route = useRoute();
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');
const code = ref('');
const modalVisible = ref(false); // 控制 Modal 显示
const selectedRows = ref<DataType[]>([]); // 存放选中的行
const onCheckboxChange = ({ records }) => {
  console.log(records)
  selectedRows.value = records;
};


const gridOptions: VxeGridProps<DataType> = {
  checkboxConfig:{
    range: true, // 可选：支持 shift 连选
   
  },
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  columns: [
    { field: 'id', title: $t('page.common.Code') ,type:'checkbox' },
    { field: 'subject', title: $t('page.common.Title') },
    { field: 'to', title: $t('admin.recipient') },
    { field: 'from', title: $t('admin.Sender') },
    {
      field: 'send_time',
      title: $t('admin.sendTime'),
    },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: $t('page.common.Action'),
      width: 240,
    },
  ],
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    total: 0,
    currentPage: 1,
    pageSize: 20,
   layouts: ['Total', 'Sizes', 'PrevPage', 'Number', 'NextPage', 'FullJump'], // 带总条数和每页大小选择
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const param = queryStringToObject(route.meta.param as string);
        if (param?.code) {
          formValues.code = param.code;
          code.value = param.code;
        }

        const { data } = await getEmailLog({
          page: page.currentPage,
          limit: page.pageSize,
          ...formValues,
        });
        const total = data.list.length;
      
        data.list = formatImagesList(data.list, 'thumbnail');
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['code'],
      },
      fieldName: 'code',
      label: 'code',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: $t('page.common.Please Enter')+` ${viewTitle}`,
      },
      fieldName: 'keyword',
      label: `${viewTitle} `+$t('page.common.Title'),
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
};
const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});

const handleDelete = async (row: DataType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deleteEmailTemplat(row.id);
    $table.remove(row);
    message.success(msg);
  }
};

const openDialog = async (row?: DataType) => {
  const id = row?.id || 0;

  router.push({
    name: `AdminemaillogDetail`,
    params: { id },
  });
};



const openDeleteConfirm = () => {

  const $table = GridApi.grid;
    const selectedRows = $table.getCheckboxRecords();
    console.log(selectedRows)
  if (selectedRows.length === 0) {
    message.warning('请先选择需要删除的项');
    return;
  }

  Modal.confirm({
    title: '确认删除',
    content: `你确定要删除选中的 ${selectedRows.length} 项吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      const ids = selectedRows.map(item => item.id);
      try {
        const { msg } = await deleteMultiple(ids); // ❗️这里是你定义的 API，传数组 ID
        const $table = GridApi.grid;
        message.success(msg || '删除成功');
        $table.commitProxy('query'); // ✅ 删除成功后刷新表格数据
      } catch (err) {
        message.error('删除失败，请稍后重试');
      }
    },
  });

  
};
</script>

<template>
  <Page auto-content-height>
    <Grid :table-title="`${viewTitle} `+ $t('page.common.List')">
      <template #toolbar-tools>
          <VbenButton @click="openDeleteConfirm()" class="mr-2">{{$t('admin.deleteSelected')}}</VbenButton>
          <Modal v-model:visible="modalVisible" title="确认删除" class="w-[600px]">
            <template #default>
              <p>你确定要删除选中的 {{ selectedRows.length }} 项吗？此操作无法恢复。</p>
            </template>
            <template #footer>
              <VbenButton @click="modalVisible = false">取消</VbenButton>
              <VbenButton type="primary" danger @click="openDeleteConfirm()">确认删除</VbenButton>
            </template>
          </Modal>
      </template>
      
      <template #action="{ row }">
        <Space>
          <Button type="primary" @click="openDialog(row)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:more-fill" />
              </span>
            </template>
            {{ $t('page.common.Details')}}
          </Button>
          <Popconfirm
            :cancel-text="$t('page.common.No')"
            :ok-text="$t('page.common.Yes')"
            :title="$t('page.common.Confirm Delete')"
            @confirm="handleDelete(row)"
          >
            <Button danger type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
              {{ $t('page.common.Delete')}}
            </Button>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
